import React, { useState, useEffect } from 'react';
import './App.css';
import Header from './components/Header';
import List from './components/List';
import Footer from './components/Footer';

function App() {
  // 状态管理待办事项, 在status中设置初始值, 初始值是一个匿名函数, 这样做的目的是为了确保状态的初始化只在组件挂载时发生一次
  // 把函数的返回值存储或更新到状态中，并不是把函数存储到状态中
  {/* 把函数返回值用箭头函数来包裹,, 然后把函数的返回值存储在状态中 */}
  const [todos, setTodos] = useState(() => {
    // 从本地存储加载待办事项
    const savedTodos = localStorage.getItem('todos');
    if (savedTodos) {
      return JSON.parse(savedTodos);
    } else {
      return [];
    }
  });

  // 当todos变化时保存到本地存储
  useEffect(() => {
    localStorage.setItem('todos', JSON.stringify(todos));
  }, [todos]);

  // 添加新的待办事项
  const addTodo = (text) => {
    const newTodo = {
      id: Date.now(),
      text,
      completed: false
    };
    setTodos([...todos, newTodo]);
  };

  // 切换待办事项的完成状态
  const toggleComplete = (id) => {
    setTodos(todos.map(todo =>
      // 如果todo的id和传入的id相同, 则返回一个新的对象, 否则返回原来的对象. 同时更改completed的属性值 
      todo.id === id ? { ...todo, completed: !todo.completed } : todo
    ));
  };

  // 删除单个待办事项
  const deleteTodo = (id) => {
    setTodos(todos.filter(todo => todo.id !== id));
  };

  // 清除所有已完成的待办事项
  const clearCompleted = () => {
    setTodos(todos.filter(todo => !todo.completed));
  };

  return (
    <div className="todo-app">
      <Header addTodo={addTodo} />
      <List 
        todos={todos} 
        toggleComplete={toggleComplete} 
        deleteTodo={deleteTodo} 
      />
      <Footer 
        todos={todos} 
        clearCompleted={clearCompleted} 
      />
    </div>
  );
}

export default App;
